package com.android.support.lib.universal.helper;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * 注；记得在配置文件里面添加如下权限：
 * <p>
 * <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
 */

public class UdpHelper {
    private static UdpHelper udpHelper;

    private UdpHelper(Context context) {
        WifiManager manager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        lock = manager.createMulticastLock("UDPwifi");//参数随便填写。
    }

    public static UdpHelper getInstance(Context context) {
        if (udpHelper == null) {
            udpHelper = new UdpHelper(context);
        }
        return udpHelper;
    }

    private Boolean BReceive = true;//是否接受数据包，true接受(默认)，false不接受
    private WifiManager.MulticastLock lock;//防止数据包无法正常接受
    private String IP = "192.168.0.1";//发送给客户端的IP地址
    // UDP服务器监听的端口（无论是服务器还是客户端，端口号都得一致）
    private Integer port = 8903;

    public Boolean getBReceive() {
        return BReceive;
    }

    public void setBReceive(Boolean BReceive) {
        this.BReceive = BReceive;
    }

    public String getIP() {
        return IP;
    }

    public void setIP(String IP) {
        this.IP = IP;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    //接口，数据包接受回调
    interface onReceive {
        void onResult(String strMsg);
    }

    /**
     * 接受数据(新开线程,根据BReceive判断，无限循环监听)
     *
     * @param onReceive 接受数据之后的回调。
     */
    public void receive(final onReceive onReceive) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                // 接收的字节大小，客户端发送的数据不能超过这个大小
                byte[] message = new byte[1024];
                try {
                    // 建立Socket连接
                    DatagramSocket datagramSocket = new DatagramSocket(port);
                    datagramSocket.setBroadcast(true);
                    DatagramPacket datagramPacket = new DatagramPacket(message,
                            message.length);
                    while (BReceive) {
                        // 准备接收数据
                        lock.acquire();//防止无法正常接受数据包
                        datagramSocket.receive(datagramPacket);//接受数据，这是一个阻塞的方法。只有接受到了数据之后，才会往下继续执行。
                        String strMsg = new String(datagramPacket.getData()).trim();//数据
                        lock.release();//lock资源释放
                        onReceive.onResult(strMsg);
                    }
                } catch (Exception e) {
                    Log.e("test", "数据接受异常:\t" + e.getMessage());
                }
            }
        }.start();
    }

    /**
     * 发送数据
     *
     * @param message
     */
    public void send(String message) {
        if (message == null || message.equals("")) {
            return;
        }
        try {
            DatagramSocket s = new DatagramSocket();
            InetAddress local = InetAddress.getByName(IP);

            int msg_length = message.length();
            byte[] messageByte = message.getBytes();
            DatagramPacket p = new DatagramPacket(messageByte, msg_length, local,
                    port);
            s.send(p);
            s.close();
        } catch (Exception e) {
            Log.e("test", "数据包发送异常:\t" + e.getMessage());
        }
    }

}
